const GET = "GET";
const POST = "POST";
const PUT = "PUT";
const FORM = "FORM";
const DELETE = "DELETE";

// 测试
const test = "http://39.99.176.36:8080";
// 生产
const prod = "https://api.linxiaobang.com.cn";
const env = wx.getAccountInfoSync().miniProgram.envVersion;
let baseURL = null;
if (env == "release") {
  baseURL = prod;
} else {
  baseURL = test;
}

const mapKey = "W3ABZ-MWZ3W-VZFRC-RUBVF-TB4DV-A7BJY";

function request(method, url, data) {
  return new Promise(function (resolve, reject) {
    let header = {
      "Content-Type": method == "POST" ? "application/x-www-form-urlencoded" : "application/json",
      "Authorization": wx.getStorageSync("token"),
    };
    wx.request({
      url: method == "POST" ? baseURL + url : url,
      method: method,
      data: data,
      header: header,
      success(res) {
        //请求成功
        //判断状态码---code状态根据后端定义来判断
        if (res.data.code == 200 || res.data.status == 0) {
          resolve(res.data);
        } else {
          //其他异常
          console.log("request error:", res.data.msg);
          if (res.data.code == 40002 || res.data.code == 40001) {
            console.log(url)
            let filter = [
              "/neighbour/api/base/user/square/post/list",
              "/neighbour/api/base/common/type"
            ];
            if (!filter.includes(url)) {
              loginHandle();
            }
          }
          if (res.data.code == 40006) {
            getApp().globalData.vant.dialog.alert({
              title: "封号状态",
              message: "因您的账号发布违规信息，或多次抢单未完成，为维护平台健康发展，做封号处理。",
              confirmButtonText: "我要申诉",
              confirmButtonColor: "#FF3D45",
              zIndex: "99999"
            }).then(() => {
              wx.navigateTo({
                url: "/pages/my/unblockedapply/unblockedapply",
              })
            });
          }
          reject(res.data);
        }
      },
      fail(err) {
        //请求失败
        // reject(err)
      }
    });
  })
}

function upload(url, fileKey, filePath, formData) {
  return new Promise(function (resolve, reject) {
    let header = {
      "Authorization": wx.getStorageSync("token"),
      "Content-Type": "multipart/form-data"
    };
    wx.uploadFile({
      url: baseURL + url,
      header: header,
      filePath: filePath,
      name: fileKey,
      formData: formData,
      success(res) {
        //请求成功
        //判断状态码---code状态根据后端定义来判断
        let data = JSON.parse(res.data);
        if (data.code == 200) {
          resolve(data);
        } else {
          //其他异常
          console.log("request error:", res.data.msg);
          if (data.code == 40002) {
            loginHandle();
          }
          reject(data);
        }
      },
      fail(err) {
        //请求失败
        console.log("request fail:", err);
        // reject(err)
      }
    })
  })
}

function loginHandle() {
  getApp().globalData.vant.dialog.alert({
    message: "您还没有登录哦~",
    confirmButtonText: "去登录",
    confirmButtonColor: "#33B868",
    zIndex: "10000"
  }).then(() => {
    wx.navigateTo({
      url: "/pages/login/login",
      success: res => {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit("token_expire")
      }
    });
  });
}

const API = {
  getPosition: (data) => request(GET, "https://apis.map.qq.com/ws/geocoder/v1/", {
    ...data,
    ...{
      key: mapKey
    }
  }),
  // 腾讯地图搜索周边小区
  getCommunity: (data) => request(GET, "https://apis.map.qq.com/ws/place/v1/search", {
    ...data,
    ...{
      key: mapKey
    }
  }),
  // 发送短信验证码
  sendMsg: (data) => request(POST, "/neighbour/api/base/common/send/msg", data),

  // 首页轮播图
  banner: (data) => request(POST, "/neighbour/api/base/common/loop/image", data),
  // 广场列表
  list: (data) => request(POST, "/neighbour/api/base/user/square/post/list", data),
  // 发布详情
  detail: (data) => request(POST, "/neighbour/api/base/user/square/post/detail", data),
  // 赚钱列表
  earn: (data) => request(POST, "/neighbour/api/base/user/square/post/list/order", data),
  // 点赞
  thumbup: (data) => request(POST, "/neighbour/api/base/dynamic/thumbup", data),
  // 点赞列表
  thumbupList: (data) => request(POST, "/neighbour/api/base/dynamic/thumbup/list", data),
  // 保存更新举报信息
  reportSave: (data) => request(POST, "/neighbour/api/base/user/save/report", data),
  // 获取举报信息
  reportGet: (data) => request(POST, "/neighbour/api/base/user/get/report", data),


  // 登录
  login: (data) => request(POST, "/neighbour/api/base/user/wx/login", data),
  // 获取个人信息
  userInfo: (data) => request(POST, "/neighbour/api/base/user/get/user_info", data),
  // 更新个人信息
  updateUserInfo: (data) => request(POST, "/neighbour/api/base/user/wx/update/user_info", data),
  // 登录
  logout: (data) => request(POST, "/neighbour/api/base/user/logout", data),

  // 文件上传
  upload: (fileKey, filePath, formData) => upload("/neighbour/api/base/files/upload", fileKey, filePath, formData),
  // 获取某个经纬度附近的小区
  getNearbyCommunity: (data) => request(POST, "/neighbour/api/base/user/nearby/community", data),
  // 获取用户附近更多小区
  getAllCommunity: (data) => request(POST, "/neighbour/api/base/user/nearby/all/community", data),
  // 保存用户选择的小区
  saveCommunity: (data) => request(POST, "/neighbour/api/base/user/save/community", data),

  // 动态发布
  squarePost: (data) => request(POST, "/neighbour/api/base/user/square/post", data),
  // 动态更新
  squareUpdate: (data) => request(POST, "/neighbour/api/base/user/square/update", data),
  // 生成押金订单的接口
  getDeposit: (data) => request(POST, "/neighbour/api/base/user/pay/deposit", data),

  // 抢单
  taskOrderTake: (data) => request(POST, "/neighbour/api/base/user/square/post/task-order/take", data),
  // 派单接单任务审核查询
  reviewList: (data) => request(POST, "/neighbour/api/base/user/square/task-order/review/list", data),
  // 派单抢单任务审核资料提交
  reviewUpdate: (data) => request(POST, "/neighbour/api/base/user/square/task-order/review/update", data),
  // 派单接单任务详情
  reviewDetail: (data) => request(POST, "/neighbour/api/base/user/square/task-order/review/detail", data),
  // 派单抢单任务批准
  reviewAudit: (data) => request(POST, "/neighbour/api/base/user/square/task-order/review/audit", data),

  // 获取用户保存的小区
  getUserCommunity: (data) => request(POST, "/neighbour/api/base/user/get/community", data),
  // 保存用户自定义的标签
  saveUserAddLabel: (data) => request(POST, "/neighbour/api/base/common/save/user/label", data),
  // 获取用户添加的标签
  getUserAddLabel: (data) => request(POST, "/neighbour/api/base/common/user/label/list", data),
  // 删除用户添加的标签
  delUserAddLabel: (data) => request(POST, "/neighbour/api/base/common/remove/user/label", data),
  // 小区认证
  communityCert: (data) => request(POST, "/neighbour/api/base/user/community/author", data),
  // 小区认证信息
  communityCertInfo: (data) => request(POST, "/neighbour/api/base/user/community/author/info", data),
  // 兼职认证
  takeOrderAuth: (data) => request(POST, "/neighbour/api/base/user/take-order/auth", data),
  // 兼职认证信息
  takeOrderAuthInfoInfo: (data) => request(POST, "/neighbour/api/base/user/take-order/auth/info", data),
  // 更新个人信息
  updateInfo: (data) => request(POST, "/neighbour/api/base/user/update/info", data),

  // 获取用户等级
  userLevel: (data) => request(POST, "/neighbour/api/base/user/level", data),
  // 获取更新信息的下拉选项
  getBaseSelectOption: (data) => request(POST, "/neighbour/api/base/common/type", data),
  // 获取邀请码
  getInviteCode: (data) => request(POST, "/neighbour/api/base/user/get/invite/code", data),
  // 获取用户状态是否被封停
  getAccountState: (data) => request(POST, "/neighbour/api/base/user/account/status", data),
  // 账号申请解封
  accountUnlock: (data) => request(POST, "/neighbour/api/base/user/account/unlock", data),
  // 意见反馈
  feedback: (data) => request(POST, "/neighbour/api/base/common/feedback", data),
  // 设置||重置 提现密码
  setPayPwd: (data) => request(POST, "/neighbour/api/base/user/set/password", data),
  // 用户提现
  getCash: (data) => request(POST, "/neighbour/api/base/user/withdraw", data),
  // 用户提现记录
  getCashRecord: (data) => request(POST, "/neighbour/api/base/user/withdraw/history", data),
  // 用户提现详情
  getCashDetail: (data) => request(POST, "/neighbour/api/base/user/out/cash/detail", data),

  // 获取上次用户选择的地址
  getAddress: (data) => request(POST, "/neighbour/api/base/common/user/last/address", data),
  // 签到
  sign: (data) => request(POST, "/neighbour/api/base/user/sign", data),
  // 过去一周的签到情况
  weekSign: (data) => request(POST, "/neighbour/api/base/user/week/sign", data),
  // 今天的任务是否完成
  todayTask: (data) => request(POST, "/neighbour/api/base/user/today/task/status", data),
  // 我的饭团
  myIntegral: (data) => request(POST, "/neighbour/api/base/user/integral", data),
  // 饭团兑换商品
  exchangeGood: (data) => request(POST, "/neighbour/api/base/common/user/exchange", data),
  // 饭团兑换记录
  exchangeGoodRecord: (data) => request(POST, "/neighbour/api/base/common/user/exchange/history", data),

  // 我的押金
  myCash: (data) => request(POST, "/neighbour/api/base/user/get/cash", data),
  // 查询每日奖励
  dailyReward: (data) => request(POST, "/neighbour/api/base/user/daily-reward/stat", data),
  // 查询VIP状态
  myVIP: (data) => request(POST, "/neighbour/api/base/user/vip/stat", data),
  // 我的动态
  myNews: (data) => request(POST, "/neighbour/api/base/user/square/post/list/myNews", data),
  // 我的动态删除（取消同步）
  cancelSync: (data) => request(POST, "/neighbour/api/base/user/square/post/cancel-sync", data),
  // 我的摊位
  myStall: (data) => request(POST, "/neighbour/api/base/user/square/post/list/myStall", data),
  // 我的摊位 下架
  stallDown: (data) => request(POST, "/neighbour/api/base/user/square/post/stall/stopselling", data),
  // 我的摊位 删除
  stallRemove: (data) => request(POST, "/neighbour/api/base/user/square/post/remove", data),


  // 我的派单
  myPost: (data) => request(POST, "/neighbour/api/base/user/square/post/list/my-post-order", data),
  // 我的抢单
  myTaken: (data) => request(POST, "/neighbour/api/base/user/square/post/list/my-taken-order", data),
  // 抢单派单详情
  reDetail: (data) => request(POST, "/neighbour/api/base/user/square/post/task-order/review/detail", data),
  // 关闭派单
  closeTaken: (data) => request(POST, "/neighbour/api/base/user/square/post/task-order/close", data),
  // 派单情况
  reList: (data) => request(POST, "/neighbour/api/base/user/square/post/task-order/review/list", data),
  // 上传凭证/申诉/审核 提交
  evidence: (data) => request(POST, "/neighbour/api/base/user/square/post/task-order/review/update", data),
  // 派单查看接单人员列表
  takenList: (data) => request(POST, "/neighbour/api/base/user/square/post/task-order/taken/list", data),

  // 我的邀请二维码
  inviteCode: (data) => request(POST, "/neighbour/api/base/user/invite/image", data),
  // 我的邀请列表
  inviteList: (data) => request(POST, "/neighbour/api/base/user/invite/detail", data),

  // 是否有支付密码
  pwdStatus: (data) => request(POST, "/neighbour/api/base/user/password/status", data),
  // 查询用户提现金额
  myCashTake: (data) => request(POST, "/neighbour/api/base/user/cash/detail", data),
  // 提升用户等级
  upLevel: (data) => request(POST, "/neighbour/api/base/user/add/level", data),
  // 订单号查询是否支付成功
  levelNotify: (data) => request(POST, "/neighbour/api/base/pay/user_level/notify", data),

  // 抢单排行榜
  leaderboard: (data) => request(POST, "/neighbour/api/base/user/square/get/leaderboard", data),


  // 活动
  // 发布作品
  sixone_distribute: (data) => request(POST, "/neighbour/api/activity/act/distribute", data),
  // 投票
  sixone_ballot: (data) => request(POST, "/neighbour/api/activity/act/ballot/" + data),
  // 获取作品
  sixone_getballot: (data) => request(POST, "/neighbour/api/activity/act/ballot/all", data),
  // 获取排行榜
  sixone_rank: (data) => request(POST, "/neighbour/api/activity/act/ranking/list", data),
  // 我的作品
  sixone_my: (data) => request(POST, "/neighbour/api/activity/act/ballot/current", data),

  // 种树
  // 签到
  tree_sign: (data) => request(POST, "/neighbour/api/activity/tree/sign", data),
  // 连续签到天数
  tree_signDays: (data) => request(POST, "/neighbour/api/activity/tree/sign/days", data),
  // 签到状态
  tree_signStatus: (data) => request(POST, "/neighbour/api/activity/tree/sign/condition", data),
  // 排行榜
  tree_rank: (data) => request(POST, "/neighbour/api/activity/tree/sign/rank", data),
  // 当前用户排名
  tree_rankMy: (data) => request(POST, "/neighbour/api/activity/tree/sign/list", data),
  // 当前用户兑换信息
  tree_exchangeInfo: (data) => request(POST, "/neighbour/api/activity/tree/sign/exchange/info", data),
  // 获取所有水果
  tree_friuteList: (data) => request(POST, "/neighbour/api/activity/tree/sign/friute", data),
  // 兑换水果
  tree_exchange: (data) => request(POST, "/neighbour/api/activity/tree/sign/exchange/friute", data),
  // 兑换记录
  tree_record: (data) => request(POST, "/neighbour/api/activity/tree/sign/exchange/history", data),
};

module.exports = {
  API: API
}